<script lang="ts" setup>
import { createVNode, onMounted, reactive, ref } from 'vue';

import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import {
  Button as AButton,
  Card as ACard,
  Col as ACol,
  Divider as ADivider,
  Form as AForm,
  FormItem as AFormItem,
  Input as AInput,
  Row as ARow,
  Space as ASpace,
  Table as ATable,
  TabPane as ATabPane,
  Tabs as ATabs,
  Tag as ATag,
  message,
  Modal,
} from 'ant-design-vue';

import {
  getCustomerHistoryList,
  getOrderHistoryList,
  getTodoHistoryList,
  revertBatch,
  revertCustomer,
  revertOrder,
  revertTodo,
} from '#/api/hm/transferHistory/api';

const activeKey = ref('customer');

// --- Utility Functions ---
const createDefaultPagination = () => ({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
});

const createDefaultSearchParams = () => ({
  customerName: '',
  newStaffName: '',
  newStoreName: '',
});

// --- State Management ---
const customerSearchParams = reactive(createDefaultSearchParams());
const orderSearchParams = reactive({ customerName: '', newSaleUserName: '' });
const todoSearchParams = reactive({ customerName: '', newTodoPersonName: '' });

const customerTable = reactive({
  loading: false,
  dataSource: [] as any[],
  pagination: createDefaultPagination(),
  columns: [
    { title: '客户姓名', dataIndex: 'customerName', width: 120 },
    { title: '原服务员工', dataIndex: 'oldStaffName', width: 120 },
    { title: '新服务员工', dataIndex: 'newStaffName', width: 120 },
    { title: '原归属店铺', dataIndex: 'oldStoreName', width: 150 },
    { title: '新归属店铺', dataIndex: 'newStoreName', width: 150 },
    { title: '操作人', dataIndex: 'operatorName', width: 120 },
    { title: '转移时间', dataIndex: 'createTime', width: 180 },
    { title: '状态', dataIndex: 'status', width: 100 },
    { title: '操作', key: 'action', width: 150, fixed: 'right' },
  ],
});

const orderTable = reactive({
  loading: false,
  dataSource: [] as any[],
  pagination: createDefaultPagination(),
  columns: [
    { title: '订单ID', dataIndex: 'saleOrderId', width: 180 },
    { title: '客户姓名', dataIndex: 'customerName', width: 120 },
    { title: '原服务员工', dataIndex: 'oldSaleUserName', width: 120 },
    { title: '新服务员工', dataIndex: 'newSaleUserName', width: 120 },
    { title: '原归属店铺', dataIndex: 'oldSaleDeptName', width: 150 },
    { title: '新归属店铺', dataIndex: 'newSaleDeptName', width: 150 },
    { title: '状态', dataIndex: 'status', width: 100 },
    { title: '操作', key: 'action', width: 100, fixed: 'right' },
  ],
});

const todoTable = reactive({
  loading: false,
  dataSource: [] as any[],
  pagination: createDefaultPagination(),
  columns: [
    { title: '待办ID', dataIndex: 'todoId', width: 180 },
    { title: '客户姓名', dataIndex: 'customerName', width: 120 },
    { title: '原待办人', dataIndex: 'oldTodoPersonName', width: 120 },
    { title: '新待办人', dataIndex: 'newTodoPersonName', width: 120 },
    { title: '状态', dataIndex: 'status', width: 100 },
    { title: '操作', key: 'action', width: 100, fixed: 'right' },
  ],
});

const tableMap = {
  customer: {
    state: customerTable,
    api: getCustomerHistoryList,
    params: customerSearchParams,
  },
  order: {
    state: orderTable,
    api: getOrderHistoryList,
    params: orderSearchParams,
  },
  todo: { state: todoTable, api: getTodoHistoryList, params: todoSearchParams },
};

// --- Core Logic ---
async function fetchData(type: 'customer' | 'order' | 'todo') {
  const target = tableMap[type];
  target.state.loading = true;
  try {
    const queryParams = {
      ...target.params,
      pageNum: target.state.pagination.current,
      pageSize: target.state.pagination.pageSize,
    };
    // Filter out empty string parameters before sending
    Object.keys(queryParams).forEach((key) => {
      if (queryParams[key] === '') {
        delete queryParams[key];
      }
    });

    const { rows, total } = await target.api(queryParams);
    target.state.dataSource = rows;
    target.state.pagination.total = total;
  } catch (error) {
    console.error(`加载${type}列表失败:`, error);
    message.error(`加载列表失败，请稍后重试`);
  } finally {
    target.state.loading = false;
  }
}

// --- Event Handlers ---
function handleTabChange(key: string) {
  const tableState = tableMap[key].state;
  // Fetch data only if the tab is switched to and has no data
  if (tableState.dataSource.length === 0) {
    fetchData(key as any);
  }
}

function handleTableChange(type: 'customer' | 'order' | 'todo', pagination) {
  tableMap[type].state.pagination = {
    ...tableMap[type].state.pagination,
    ...pagination,
  };
  fetchData(type);
}

function handleSearch(type: 'customer' | 'order' | 'todo') {
  tableMap[type].state.pagination.current = 1;
  fetchData(type);
}

function handleReset(type: 'customer' | 'order' | 'todo') {
  const params = tableMap[type].params;
  Object.keys(params).forEach((key) => {
    params[key] = '';
  });
  handleSearch(type);
}

function showRevertConfirm(
  type: 'batch' | 'customer' | 'order' | 'todo',
  record: Recordable,
) {
  const titleMap = {
    batch: '确认全部撤销？',
    customer: '确认撤销此客户转移记录？',
    order: '确认撤销此订单转移记录？',
    todo: '确认撤销此待办转移记录？',
  };
  const contentMap = {
    batch: `此操作将撤销与客户 [${record.customerName}] 本次相关的所有转移，数据将恢复到转移前的状态。`,
    customer: '此操作仅撤销本条客户的归属关系，不影响关联的订单和待办。',
    order: `此操作将撤销订单 [${record.saleOrderId}] 的归属关系。`,
    todo: `此操作将撤销待办 [${record.todoId}] 的归属关系。`,
  };

  Modal.confirm({
    title: titleMap[type],
    icon: createVNode(ExclamationCircleOutlined),
    content: contentMap[type],
    okText: '确认撤销',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        switch (type) {
          case 'batch': {
            await revertBatch(record.customerTransferHistoryId);
            break;
          }
          case 'customer': {
            await revertCustomer(record.customerTransferHistoryId);
            break;
          }
          case 'order': {
            await revertOrder(record.orderTransferHistoryId);
            break;
          }
          case 'todo': {
            await revertTodo(record.todoTransferHistoryId);
            break;
          }
        }
        // message.success('撤销成功!');
        fetchData('customer');
        fetchData('order');
        fetchData('todo');
      } catch (error) {
        console.error('撤销操作失败:', error);
        // Backend should provide specific error messages, if not, show generic one
        // message.error(error.message || '撤销失败');
      }
    },
  });
}

// --- Lifecycle ---
onMounted(() => {
  fetchData('customer');
});
</script>

<template>
  <div class="p-4">
    <ACard title="转移历史记录" :bordered="false">
      <ATabs
        v-model:active-key="activeKey"
        type="card"
        @change="handleTabChange"
      >
        <!-- Customer History Tab -->
        <ATabPane key="customer" tab="客户转移记录">
          <div class="table-page-search-wrapper">
            <!-- Customer Search Form -->
            <AForm :model="customerSearchParams">
              <ARow :gutter="24">
                <ACol :span="6">
                  <AFormItem label="客户姓名">
                    <AInput
                      v-model:value="customerSearchParams.customerName"
                      placeholder="请输入客户姓名"
                      allow-clear
                      @press-enter="handleSearch('customer')"
                    />
                  </AFormItem>
                </ACol>
                <ACol :span="6">
                  <AFormItem label="新服务员工">
                    <AInput
                      v-model:value="customerSearchParams.newStaffName"
                      placeholder="请输入员工姓名"
                      allow-clear
                      @press-enter="handleSearch('customer')"
                    />
                  </AFormItem>
                </ACol>
                <ACol :span="6">
                  <AFormItem label="新归属店铺">
                    <AInput
                      v-model:value="customerSearchParams.newStoreName"
                      placeholder="请输入店铺名称"
                      allow-clear
                      @press-enter="handleSearch('customer')"
                    />
                  </AFormItem>
                </ACol>
                <ACol :span="6">
                  <AFormItem>
                    <ASpace>
                      <AButton type="primary" @click="handleSearch('customer')">
                        查询
                      </AButton>
                      <AButton @click="handleReset('customer')">重置</AButton>
                    </ASpace>
                  </AFormItem>
                </ACol>
              </ARow>
            </AForm>
          </div>

          <!-- Customer Table -->
          <ATable
            class="mt-4"
            :columns="customerTable.columns"
            :row-key="(record) => record.customerTransferHistoryId"
            :data-source="customerTable.dataSource"
            :pagination="customerTable.pagination"
            :loading="customerTable.loading"
            @change="handleTableChange('customer', $event)"
            bordered
            size="middle"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'status'">
                <ATag :color="record.status === '1' ? 'red' : 'green'">
                  {{ record.status === '1' ? '已撤销' : '正常' }}
                </ATag>
              </template>
              <template v-if="column.key === 'action'">
                <ASpace>
                  <a
                    @click="showRevertConfirm('customer', record)"
                    class="text-blue-500"
                    v-if="record.status === '0'"
                  >
                    撤销
                  </a>
                  <ADivider type="vertical" v-if="record.status === '0'" />
                  <a
                    class="text-red-500"
                    @click="showRevertConfirm('batch', record)"
                    v-if="record.status === '0'"
                  >
                    全部撤销
                  </a>
                </ASpace>
              </template>
            </template>
          </ATable>
        </ATabPane>

        <!-- Order History Tab -->
        <ATabPane key="order" tab="订单转移记录">
          <div class="table-page-search-wrapper">
            <!-- Order Search Form -->
            <AForm :model="orderSearchParams">
              <ARow :gutter="24">
                <ACol :span="6">
                  <AFormItem label="客户姓名">
                    <AInput
                      v-model:value="orderSearchParams.customerName"
                      placeholder="请输入客户姓名"
                      allow-clear
                      @press-enter="handleSearch('order')"
                    />
                  </AFormItem>
                </ACol>
                <ACol :span="6">
                  <AFormItem label="新服务员工">
                    <AInput
                      v-model:value="orderSearchParams.newSaleUserName"
                      placeholder="请输入员工姓名"
                      allow-clear
                      @press-enter="handleSearch('order')"
                    />
                  </AFormItem>
                </ACol>
                <ACol :span="6">
                  <AFormItem>
                    <ASpace>
                      <AButton type="primary" @click="handleSearch('order')">
                        查询
                      </AButton>
                      <AButton @click="handleReset('order')">重置</AButton>
                    </ASpace>
                  </AFormItem>
                </ACol>
              </ARow>
            </AForm>
          </div>

          <!-- Order Table -->
          <ATable
            class="mt-4"
            :columns="orderTable.columns"
            :row-key="(record) => record.orderTransferHistoryId"
            :data-source="orderTable.dataSource"
            :pagination="orderTable.pagination"
            :loading="orderTable.loading"
            @change="handleTableChange('order', $event)"
            bordered
            size="middle"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'status'">
                <ATag :color="record.status === '1' ? 'red' : 'green'">
                  {{ record.status === '1' ? '已撤销' : '正常' }}
                </ATag>
              </template>
              <template v-if="column.key === 'action'">
                <a
                  @click="showRevertConfirm('order', record)"
                  class="text-red-500"
                  v-if="record.status === '0'"
                >
                  撤销
                </a>
              </template>
            </template>
          </ATable>
        </ATabPane>

        <!-- Todo History Tab -->
        <ATabPane key="todo" tab="待办转移记录">
          <div class="table-page-search-wrapper">
            <!-- Todo Search Form -->
            <AForm :model="todoSearchParams">
              <ARow :gutter="24">
                <ACol :span="6">
                  <AFormItem label="客户姓名">
                    <AInput
                      v-model:value="todoSearchParams.customerName"
                      placeholder="请输入客户姓名"
                      allow-clear
                      @press-enter="handleSearch('todo')"
                    />
                  </AFormItem>
                </ACol>
                <ACol :span="6">
                  <AFormItem label="新待办人">
                    <AInput
                      v-model:value="todoSearchParams.newTodoPersonName"
                      placeholder="请输入员工姓名"
                      allow-clear
                      @press-enter="handleSearch('todo')"
                    />
                  </AFormItem>
                </ACol>
                <ACol :span="6">
                  <AFormItem>
                    <ASpace>
                      <AButton type="primary" @click="handleSearch('todo')">
                        查询
                      </AButton>
                      <AButton @click="handleReset('todo')">重置</AButton>
                    </ASpace>
                  </AFormItem>
                </ACol>
              </ARow>
            </AForm>
          </div>

          <!-- Todo Table -->
          <ATable
            class="mt-4"
            :columns="todoTable.columns"
            :row-key="(record) => record.todoTransferHistoryId"
            :data-source="todoTable.dataSource"
            :pagination="todoTable.pagination"
            :loading="todoTable.loading"
            @change="handleTableChange('todo', $event)"
            bordered
            size="middle"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'status'">
                <ATag :color="record.status === '1' ? 'red' : 'green'">
                  {{ record.status === '1' ? '已撤销' : '正常' }}
                </ATag>
              </template>
              <template v-if="column.key === 'action'">
                <a
                  @click="showRevertConfirm('todo', record)"
                  class="text-red-500"
                  v-if="record.status === '0'"
                >
                  撤销
                </a>
              </template>
            </template>
          </ATable>
        </ATabPane>
      </ATabs>
    </ACard>
  </div>
</template>

<style scoped>
.p-4 {
  padding: 16px;
}

.table-page-search-wrapper {
  padding: 16px;
  background-color: #fafafa;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
